//
//  customCells.m
//  CMS
//
//  Created by Vuong Van Khanh on 11/1/12.
//  Copyright (c) 2012 Rikkei. All rights reserved.
//

#import "customCells.h"
#import "StoreVars.h"
#import "ASIHTTPRequest.h"
#import "GDataXMLNode.h"
#import "Parser.h"
#import "downloadInfo.h"
#import "xml_userDownload_writer.h"
#import "SSZipArchive.h"
#import "ASINetworkQueue.h"

@interface customCells()
@property (strong, nonatomic) ASIHTTPRequest *request;
@end

@implementation customCells
@synthesize request;
@synthesize title = _title;
@synthesize btnDownload = _btnDownload;
@synthesize lbid = _lbid;
@synthesize downloadLink = _downloadLink;
@synthesize progressView = _progressView;
//@synthesize aQueue;
//show alert method
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    [alertView show];
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}
- (void) btnDownloadClicked:(id)sender{
    NSError *error;
//    NSLog(@"button download clicked with id %@ and download link %@", _lbid.text, _downloadLink.text);
    NSString *downloadDir = [StoreVars sharedInstance].downloadDir;
    if(!downloadDir){
        //create folder to store downloaded data from server
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
        NSString *downloadDir = [documentsDirectory stringByAppendingPathComponent:[StoreVars sharedInstance].username];
        
        //Create folder
        if (![[NSFileManager defaultManager] fileExistsAtPath:downloadDir])
            [[NSFileManager defaultManager] createDirectoryAtPath:downloadDir withIntermediateDirectories:NO attributes:nil error:&error];
        [StoreVars sharedInstance].downloadDir = downloadDir;
        NSLog(@"create dataStore director at file downloading");
    }
    NSURL *url = [NSURL URLWithString:_downloadLink.text];
    [_progressView setHidden:NO];
    
    self.request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request setTimeOutSeconds:15];
    [request setNumberOfTimesToRetryOnTimeout:2];
    [request setDownloadDestinationPath:[[downloadDir stringByAppendingPathComponent:_lbid.text] stringByAppendingString:@".zip"]];
    [request setDelegate:self];
    [request setDownloadProgressDelegate:_progressView];
    [request setShouldContinueWhenAppEntersBackground:YES];
    [request setShowAccurateProgress:YES];
    [request startAsynchronous];
    [_btnDownload setEnabled:NO];
    [_btnDownload setTitle:@"Downloading..." forState:UIControlStateDisabled];
    [_btnDownload setTitleColor:[UIColor grayColor]  forState:UIControlStateDisabled];
   
    
    if (error) {
        NSLog(@"%@", error);
        [self alertStatus:@"Error when downloading, Please contact with administrator!" :@"Error"];
        return;
    }
}

-(void)requestFinished:(ASIHTTPRequest *)request
{
    //write userDownloaded xml file
//    downloadInfo *downloaded        =   [[downloadInfo alloc] init];
//    xml_userDownload_writer *writer =   [[xml_userDownload_writer alloc] initWithData:[StoreVars sharedInstance].username documentid:_lbid.text];
//    [downloaded.downloader addObject:writer];
//    [Parser writeFile:downloaded];
    
    //extract zip file
    NSString *downloadDir = [StoreVars sharedInstance].downloadDir;
    NSString *path = [[downloadDir stringByAppendingPathComponent:_lbid.text] stringByAppendingString:@".zip"];
    [SSZipArchive unzipFileAtPath:path toDestination: downloadDir];
    [_btnDownload setHidden:YES];
    
    NSLog(@"download successed!");
    // remove zip file after download successed
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
-(void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"%@",self.request.error);
    [self alertStatus:@"Error while downloading, Please contact with administrator!" :@"Error!"];
    [self.request clearDelegatesAndCancel];
}

- (void)dealloc{
    [self.request clearDelegatesAndCancel];
}
@end
